/**
 * 登录路由事件处理
 */

const userModel = require('../models/userModel')
const RSA = require('../rsa/rsa')
var vertoken = require('../token/token')


// 登录验证，下发token
function verification(data) {
  // 验证账号密码是否合理
  return new Promise((resolve, reject) => {
    userModel.findOne({ user_name: data.name }, (err, res) => {
      if (err) {
        reject(err)
      } else {
        resolve(res)
      }
    })
  }).then(res => {
    if (!res) {
      return { msg: '账号不存在', code: 404 }
    } else if (RSA.decrypt(res.user_password !== RSA.decrypt(data.password))) {
      return {msg: '密码错误', code: 200}
    } else {
      // 下发token
      return new Promise((resolve, reject) => {
        const params = [];
        params[0] = data.name
        params[1] = res.user_id
        //调用生成token的方法
        vertoken.setToken(...params).then(token => {
          //前端获取token后存储在localStroage中,
          //**调用接口时 设置axios(ajax)请求头Authorization的格式为`Bearer ` +token
          resolve({ code: 200, msg: '登录成功', token: token, profile: res })
        })
      })
    }
  }).catch(err => {
    console.log(err)
    return err
  }).then(res => {
    return res
  })
}


module.exports = {
  verification
}
